<template>
  <view class="authorize-container">
    <!-- Logo和标题区域 -->
    <view class="header">
      <image
        src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/3837e31b236d46578dcc41d49904568e.png"
        class="logo"
      />
      <text class="title">博阳荟</text>
    </view>

    <!-- 按钮区域 -->
    <view class="button-container">
      <!-- 登录按钮 -->
      <button
        class="authorize-btn"
        open-type="getUserInfo"
        withCredentials="true"
        @click="handleWechatAuthorize"
      >
        微信登录
      </button>

      <!-- 取消按钮 -->
      <!-- <button class="cancel-btn" @click="handleCancel">取消</button> -->
    </view>

    <wd-toast />
  </view>
</template>

<script lang="ts" setup>
import UserAPI from "@/api/system/user";
import { useToast } from "wot-design-uni";
import AuthAPI from "@/api/auth";
import { ref, onMounted } from "vue";
const toast = useToast();
const loading = ref(false);
import { setToken, setUserInfo } from "@/utils/cache";

import getRouteParams from "@/utils/getParams";
// 检查是否有注册成功参数
const registerSuccess = (() => {
  try {
    const routeParams = getRouteParams();
    if (routeParams.query && typeof routeParams.query === "object") {
      const query = routeParams.query as Record<string, any>;
      return query.registerSuccess || null;
    }
    return null;
  } catch (error) {
    console.error("获取注册成功参数失败:", error);
    return null;
  }
})();

// 处理用户信息获取成功 - 暂时注释掉未使用的函数
// const getUserInfoSuccess = (_userInfoRes: any) => {
//   // 用户同意授权后，调用登录API
//   handleWechatLogin();
// };

// 处理从微信授权返回的code
const handleWechatAuthCallback = (code: string) => {
  try {
    // 尝试从URL中获取code参数
    if (code) {
      loading.value = true;

      // 使用获取到的code调用登录API
      AuthAPI.wxGongzLogin(code)
        .then((data) => {
          if (data) {
            setToken(data.accessToken);
            // 检查用户是否完善了用户信息
            checkUserProfile();
          }
        })
        .catch((error: any) => {
          console.error("微信授权回调处理失败:", error);
          toast.error(error?.message || "微信登录失败，请重试");
        })
        .finally(() => {
          loading.value = false;
        });
    }
  } catch (error: any) {
    console.error("获取URL参数失败:", error);
  }
};

// 页面加载时检查是否有微信授权回调
onMounted(() => {
  try {
    // 优先使用getRouteParams获取code参数（跨平台兼容方式）
    const routeParams = getRouteParams();
    let code: string | null = null;

    // 尝试从query中获取code参数
    if (routeParams.query && typeof routeParams.query === "object") {
      const query = routeParams.query as Record<string, any>;
      code = query.code || query.Code || null;
    }

    // 如果没有获取到code，且在H5环境下，尝试从URL中获取
    if (!code && typeof window !== "undefined" && window.location) {
      const urlParams = new URLSearchParams(window.location.search);
      code = urlParams.get("code");
    }

    // 如果获取到code参数，执行授权回调处理
    if (code) {
      handleWechatAuthCallback(code);
    }
  } catch (error: any) {
    console.error("页面加载时获取路由参数失败:", error?.message || error);
  }
});

// 微信授权登录处理
const handleWechatAuthorize = (_userInfoRes: any) => {
  if (loading.value) return;
  loading.value = true;
  try {
    // 获取系统信息对象，判断当前运行环境
    const systemInfo = uni.getSystemInfoSync();
    // 判断是否为H5环境
    const isH5 = systemInfo.uniPlatform === "web";

    console.log(isH5, "isH5", systemInfo.uniPlatform, "systemInfo.uniPlatform");
    if (isH5) {
      // H5环境：调用getWxLoginUrl接口
      AuthAPI.getWxLoginUrl()
        .then((res: any) => {
          if (res) {
            // 跳转到微信授权登录页面
            window.location.href = res;
            console.log("跳转到微信授权登录页面:", res);
          } else {
            throw new Error("获取微信登录URL失败");
          }
        })
        .catch((error: any) => {
          console.error("H5微信登录处理失败:", error);
          toast.error(error?.message || "微信登录失败，请重试");
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      // 小程序环境：调用微信登录接口
      uni.login({
        provider: "weixin",
        onlyAuthorize: true, // 仅请求授权认证，这会显示微信登录页面
        success: (res) => {
          try {
            if (res.code) {
              AuthAPI.wechatLogin(res.code).then((data) => {
                if (data) {
                  setToken(data.accessToken);
                  // 检查用户是否完善了用户信息
                  checkUserProfile();
                }
              });
            } else {
              throw new Error("获取微信登录code失败: " + (res.errMsg || "未知错误"));
            }
          } catch (error: any) {
            console.error("微信登录处理失败:", error);
            toast.error(error?.message || "微信登录失败，请重试");
          } finally {
            loading.value = false;
          }
        },
        fail: (err) => {
          console.error("uni.login失败:", err);
          toast.error("微信登录失败，请重试");
          loading.value = false;
        },
      });
    }
  } catch (error: any) {
    console.error("获取系统信息失败:", error);
    toast.error("获取系统信息失败，请重试");
    loading.value = false;
  }
};

// 微信登录判断是否已经完善了用户信息
const checkUserProfile = () => {
  UserAPI.getProfile().then((res: any) => {
    // 显示获取微信授权成功提示
    toast.success("获取微信授权成功");
    if (res) {
      // 将用户信息存储到本地缓存中
      setUserInfo(res);
      if (!res.baseFlag && !registerSuccess) {
        // 如果baseFlag为false，跳转到完善信息页面
        setTimeout(() => {
          uni.navigateTo({
            url: "/pages/login/wx-complete-profile",
          });
        }, 1000);
      } else {
        // 如果baseFlag为true，直接跳转到首页
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/index/index",
          });
        }, 1000);
      }
    }
  });
};
// 取消登录
const handleCancel = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.authorize-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  background-color: #f8f8f8;
}

.header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 200rpx;
  margin-bottom: 150rpx;
}

.logo {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 30rpx;
}

.title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
}

.button-container {
  width: 80%;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.authorize-btn {
  width: 100%;
  height: 90rpx;
  font-size: 32rpx;
  line-height: 90rpx;
  color: #fff;
  background-color: #07c160;
  border: none;
  border-radius: 45rpx;
}

.authorize-btn:active {
  background-color: #06b255;
}

.cancel-btn {
  width: 100%;
  height: 90rpx;
  font-size: 32rpx;
  line-height: 90rpx;
  color: #666;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 45rpx;
}

.cancel-btn:active {
  background-color: #f5f5f5;
}
</style>
